import logging
import sys
# logging.debug("debug=====")  # debug  调试
# logging.info("info!!!!!!!!!!!") # info  信息
# logging.warning("warning!!!!!!!!!!!") # warning  警告
# logging.error("error!!!!!!!!!!!") # error  错误/异常
# logging.critical("critical!!!!!!!!!!!") # critical  严重/致命

# 日志收集器
from datetime import datetime


class Logger:

    def __init__(self):
        # 创建日志收集器
        self.logger = logging.getLogger("自动化测试日志")
        # 设置日志收集器 的日志级别是  debug
        self.logger.setLevel('DEBUG')

    def log(self, level, msg):
        # 日志格式:
        # ERROR-2022-05-25 09:41:33 logg.py  34   元素定位成功
        format = logging.Formatter('%(levelname)s - %(asctime)s - %(filename)s - %(lineno)d - %(message)s')
        # 创建输出方式
        if level == 'info':
            stream = sys.stdout
        else:
            stream = None
        sh = logging.StreamHandler(stream=stream)
        sh.setFormatter(format)
        sh.setLevel('DEBUG')

        # 获取收集日志的时间
        filename = datetime.now().date()

        # 创建收集方式
        fh = logging.FileHandler('./lib/logs/'+str(filename)+'.log', encoding='UTF8')
        fh.setFormatter(format)
        fh.setLevel('DEBUG')

        # 将收集方式和输出方式 与 收集器绑定
        self.logger.addHandler(sh)
        self.logger.addHandler(fh)

        if level == "debug":
            self.logger.debug(msg)
        elif level == 'info':
            self.logger.info(msg)
        elif level == 'warning':
            self.logger.warning(msg)
        elif level == 'error':
            self.logger.error(msg)
        elif level == 'critical':
            self.logger.critical(msg)

        # 释放收集方式与输出方式
        self.logger.removeHandler(sh)
        self.logger.removeHandler(fh)

    def debug(self, msg):
        self.log('debug', msg)

    def info(self, msg):
        self.log('info', msg)

    def warning(self, msg):
        self.log('warning', msg)

    def error(self, msg):
        self.log('error', msg)

    def critical(self, msg):
        self.log('critical', msg)

if __name__ == '__main__':
    logger = Logger()

    # logger.log('debug', "debug1111111")
    # logger.log('info', "info222222")
    # logger.log('warning', "warning1111111")
    # logger.log('error', "error1111111")
    # logger.log('critical', "critical1111111")

    logger.debug('debug测试')
    logger.info('info测试')
    logger.warning('warning测试')
    logger.error('error测试')
    logger.critical('critical111')